import {
  addGoodsToCart,
  cartListCount
} from "@mall/api/shopCart"
import {
  getGoodActivity,
  bookingMarketing,
  activityNoticeFn
} from "@src/api/marketing";
import {
  getGoodDetail,
  getGoodsActiveList,
  queryGoodsNeedMember
} from '@mall/api/good'
import {
  preOrderFun,
  getShopStatus
} from '@mall/api/order'
import {
  storeBindingsBehavior
} from "mobx-miniprogram-bindings";

import handleJoinGroup from "./handleJoinGruop"
import mall from "@src/store/mall";
import router from "@src/router";
import base from "@src/store/base";
import location from '@src/store/location'
import member from "@src/store/member";
import wxUtils from "@src/common/wxUtils";
import dayjs from "dayjs";
import {
  getWxaMsgTpl,
  getUserPhone
} from "@src/api/base";
import {
  getGroupRecommends
} from "@src/api/group"

Component({
  behaviors: [storeBindingsBehavior, handleJoinGroup],
  storeBindings: [{
    store: base,
    fields: ['isiPhoneX', 'themeColor', 'themeTitleColor', 'titleColor', 'statusBarHeight', 'navBarHeight', "homePage"]
  }, {
    store: member,
    fields: {
      "isMember": "isMember",
      "memberStatus": "status",
      "cardId": "categoryId"
    }
  }, {
    store: mall,
    fields: ['curLocation'],
    actions: ['initLocation', 'checkAuth', 'setStoreId']
  }, {
    store: location,
    actions: ['setAuth']
  }],
  data: {
    //搭配商品數組
    collList: [],
    //搭配商品清单
    goodsBargains: [],
    loading: true,
    //店铺服务参数
    storeServiceList: null,
    hiddentost: true,
    showSkuDialog: false,
    showGoodActivityDialog: false,
    //商品状态
    goodsStatus: 0,
    goods: null,
    //给子组件的规格列表
    specList: [],
    //sku列表
    skuList: [],
    //已选sku对象
    selectSkuObj: null,
    refreshSkuInfo: true,
    //用来展示的最低价格对象
    showPriceObj: null,
    //商品总对象
    originalGoodsObj: null,
    goodsObj: null,
    goodsType: null,
    //商品配送类型
    type: null,
    //预下单编号
    preNo: null,
    goodsId: null,
    //店铺配置
    storeConfig: {},
    token: null,
    tempdata: null,
    //购买提示
    buyingTips: null,
    tostState: null,
    firstShow: true,
    storeList: [],
    hasOtherStore: false,
    //商品活动列表
    activeList: null,
    snCode: null,
    storeNo: null,
    goodsTypeNew: null,
    collStatus: false, //判断是否是搭配商品
    activityInfo: {}, //秒杀或者拼团当前的活动对象
    // selSkuActive:{},//选择的sku有的活动
    skillHours: null, //时
    skillMinutes: null, //分
    skillSeconds: null, //秒
    skillDays: null,
    setInterValName: null,
    // subscribeTimeArr:null,//预约的数组
    bookingStatus: false, //当前时间是否有秒杀
    shopCarInfo: {}, //购物车传过来的数据用于触发数据回显数据
    groupShopType: "openGroup", //拼团类型 用于传入弹窗
    groupList: null, //该商品全部拼团活动拼团活动


    joinSpellGroupInfo: null, //点击参加拼团相关信息
    joinSpellGroupStatue: false, //判断是否是从参加拼团进来的
    togetherGroupInfo: null, //点击凑团相关信息
    groupNo: null, //参加别人 入团
    joinGroupStatus: false, //判断当前是否是加入团的拼团，
    groupActivityNo: null, //参加团 的ActivityNo
    oneselfGroup: true, //是否单独购买
    groupShopStatus: false,
    groupRecommends: [],
    // featureGroupList:[],
    // featureGroupBookingList:[],

    secKillActivityList: [],
    quickSkillItem: null, //正常商品时 其他sku有秒杀的项
    groupActivityList: [],
    secKillBookingNoticeActivity: null,
    secKillBookingNotice: [],
    secKillBookingNoticeActive: null,
    groupBookingNotice: [],
    joinGroupPageInfo: null, //参团页面进来带来的团相关信息
    hasSecKillSkuActivityMap: null,
    shopCarInfoNum: 0, //购物车信息执行过弹窗显示没
    isOpenTime: true,
    deliveryTypeShow:true

  },
  observers: {
    'goodsTypeNew': function (v) {
      this.setData({
        refreshSkuInfo: true
      })
    },
  },
  methods: {
    onLoad: function (options) {
      if (options.collStatus) {
        this.setData({
          collStatus: true
        })
      }
      if (options.tempdata) {
        this.setData({
          tempdata: JSON.parse(options.tempdata),
        })
      } else {
        this.setData({
          tempdata: options,
        })
      }
      const eventChannel = this.getOpenerEventChannel();
      const that = this;
      //从参加拼团页面进入
      if (options.groupNo) {
        eventChannel.on('joinGroupToGoodDetails', (data) => {
          this.setData({
            joinSpellGroupInfo: options,
            joinSpellGroupStatue: true,
            joinGroupPageInfo: data,
            ['selectSkuObj.skuId']: data.skuId
          })
        })
      }
      //从购物车页面进来
      if (Object.keys(eventChannel).length) {
        eventChannel.on('toGoodsDetailParams', (data) => {
          const shopCarInfo = data.data
          if (Object.keys(shopCarInfo).length) {
            that.setData({
              tempdata: shopCarInfo,
              shopCarInfo: shopCarInfo,
            });
          }
        })
      }

    },

    // getOption(){
    //   let pages = getCurrentPages()    //获取加载的页面
    //   let currentPage = pages[pages.length-1]    //获取当前页面的对象
    //   let options = currentPage.options    //如果要获取url中所带的参数可以查看options
    //   let option = ""
    //   Object.keys(options).forEach((item)=>{option+=item+"="+options[item]+"&"})
    //   option=option.slice(0,option.length-1)
    //   this.setData({optionKey:option})


    onLogin() {
      wx.nextTick(() => {
        this.getGoodsDetailFun(this.data.tempdata);
      })
      this.cartListCountFunc();
      this.initLocation(false, false).catch(error => { });
    },

    // 获取手机号
    getPhoneNumber(e) {
      console.log(e)
      if (!e.detail.iv) {
        // wx.showToast({title: "手机号获取失败，请重试", icon: "none", duration: 1500});
        return;
      }
      let data = {
        ivStr: e.detail.iv,
        encryptedData: e.detail.encryptedData,
      }
      getUserPhone(data).then(res => {
        if (res.code === 0) {
          this.handleBookingMarketing(null, res.data)
        } else {
          wx.showToast({
            title: "手机号获取失败，请重试",
            icon: "none",
            duration: 1500
          });
        }
      })
    },

    // 设置预约Index
    setSecKillBookingNoticeActive(e) {
      if (e.currentTarget.dataset.bookdate) {
        this.setData({
          'secKillBookingNoticeActive': e.currentTarget.dataset.bookdate
        })
      } else {
        this.setData({
          'secKillBookingNoticeActive': null
        })
      }
    },

    // 预约
    async handleBookingMarketing(e, phone = null) {
      let noticeParams = null
      if (this.data.secKillBookingNoticeActivity.booking && !this.data.secKillBookingNoticeActivity.bookingStatus) {
        let params = {
          phone,
          serialNo: this.data.secKillBookingNoticeActivity.activityNo,
          storeId: this.data.storeConfig.storeId,
          type: 1,
        }
        await bookingMarketing(params).then(res => {
          wx.showToast({
            title: '预约成功',
            duration: 1000
          })
          if (this.data.secKillBookingNoticeActive) {
            noticeParams = {
              noticeTime: this.data.secKillBookingNoticeActive,
              serialNo: this.data.secKillBookingNoticeActivity.activityNo,
              storeId: this.data.storeConfig.storeId
            }
          }
          // phone?this.addRemindModel():this.addRemind()
          this.setData({
            ['activityInfo.bookingStatus']: 1
          })
          this.setData({
            ['secKillBookingNoticeActivity.bookingStatus']: 1
          })
          this.data.secKillActivityList.some((v, i) => {
            let todoParams = `secKillActivityList[${i}].bookingStatus`
            if (v.activityNo === this.data.secKillBookingNoticeActivity.activityNo) this.setData({
              [todoParams]: 1
            })
          })
        }).catch(() => {
          wx.hideLoading()
        })
      }

      if (e.currentTarget.dataset.bookdate) {
        const bookDate = e.currentTarget.dataset.bookdate;
        noticeParams = {
          noticeTime: bookDate,
          serialNo: this.data.secKillBookingNoticeActivity.activityNo,
          storeId: this.data.storeConfig.storeId
        }
      }

      // 判断提醒我
      if (noticeParams) {
        activityNoticeFn(noticeParams).then(res => {
          phone ? this.addRemindModel() : this.addRemind()
        })
      }
    },
    //商品活动预约
    handleActivityNoticeFn(e) {
      const bookDate = e.currentTarget.dataset.bookdate;
      const data = {
        noticeTime: bookDate,
        serialNo: this.data.secKillBookingNoticeActivity.activityNo,
        storeId: this.data.storeConfig.storeId
      }
      activityNoticeFn(data).then(res => {
        this.addRemind()
      })
    },

    addRemind() {
      getWxaMsgTpl({
        bizCode: "SECKILL_ACTIVITY_NOTICE_SUBSCRIBE"
      }).then(res => {
        wxUtils.requestSubscribeMessage(res.data).then(result => {
          if (result[res.data[0]] === "accept") {
            wx.showToast({
              title: "订阅提醒成功",
              icon: "success",
              duration: 1500
            })
          }
        })
      });
    },

    // 提醒我
    addRemindModel() {
      wx.showModal({
        title: '温馨提示',
        content: '是否订阅秒杀商品开始通知提醒？',
        confirmText: "是",
        cancelText: "否",
        success: function (res) {
          if (res.confirm) {
            getWxaMsgTpl({
              bizCode: "SECKILL_ACTIVITY_NOTICE_SUBSCRIBE"
            }).then(res => {
              wxUtils.requestSubscribeMessage(res.data).then(result => {
                if (result[res.data[0]] === "accept") {
                  wx.showToast({
                    title: "订阅提醒成功",
                    icon: "success",
                    duration: 1500
                  })
                }
              })
            });
          } else if (res.cancel) { }
        }
      });
    },

    //获取活动优惠
    getGoodActivityFun(params) {
      if (params) {
        getGoodActivity(params).then(res => {
          this.setData({
            activeList: res.data
          })
        })
      }
    },
    //获取商品详情数据
    getGoodsDetailFun(params) {
      this.data.refreshSkuInfo = true
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      console.log('getGoodsDetailFun', params)
      this.setData({
        activityInfo: null,
        memberType: null,
        cardList: null,
        goodsTypeNew: null,
        bookingStatus: 0,
        secKillActivityList: [],
        groupActivityList: [],
        secKillBookingNoticeActivity: null,
        secKillBookingNotice: [],
        secKillBookingNoticeActive: null,
        groupBookingNotice: [],
        groupRecommends: []
      })
      clearInterval(this.data.setInterValName)
      //判断是否携带了skuId
      if (params.skuId) {
        this.setData({
          ["selectSkuObj.skuId"]: params.skuId
        })
      }
      getGoodDetail(params).then(res => {
        console.log('获取商品详情', res)
        let goodsObj = res.data;
        let storeServiceList = goodsObj.storeConfig.serviceList.concat(goodsObj.goods.serviceList)
        let deliveryType = null;
        if (goodsObj.virtual) {
          // 虚拟商品
          deliveryType = 'VIRTUAL'
          goodsObj.deliveryTypes = ['VIRTUAL']
          goodsObj.goodsDelivery =  ['VIRTUAL']
        } else if (goodsObj.goodsDelivery && goodsObj.goodsDelivery.length > 0) {
          deliveryType = goodsObj.goodsDelivery[0].deliveryType;
          goodsObj.deliveryTypes = []
          goodsObj.goodsDelivery.forEach(v => {
            goodsObj.deliveryTypes.push(v.deliveryType)
          })
        } else {
          goodsObj.deliveryTypes = []
        }
        // 判断限购
        goodsObj.buyNumLimit = -1
        // goodsObj.secKillBuyNumLimit=-1
        if (goodsObj.goodsBuyRule && goodsObj.goodsBuyRule.limited) {
          let buyNumLimit = goodsObj.goodsBuyRule.limitNum - goodsObj.goodsBuyRule.buyNum
          goodsObj.buyNumLimit = buyNumLimit < 0 ? 0 : buyNumLimit
        } else {
          goodsObj.buyNumLimit = -1
        }
        // 格式化数据
        goodsObj.skuListMap = {}
        goodsObj.skuListIds = []
        goodsObj.skuInfo.skuList.forEach(sku => {
          goodsObj.skuListIds.push(sku.skuId)
          goodsObj.skuListMap[sku.skuId] = sku
        })
        // console.log('商品限购buyNumLimit',goodsObj.buyNumLimit)
        this.setData({
          goodsBargains: goodsObj.goodsBargains,
          barCode: goodsObj.barCode,
          deliveryType: deliveryType,
          goods: goodsObj.goods,
          goodsStatus: goodsObj.goodsStatus,
          //100: 普通商品, 200: 虚拟商品卡券
          goodsType: goodsObj.goodsType,
          goodsDelivery: goodsObj.goodsDelivery,
          skuList: goodsObj.skuInfo.skuList,
          specList: goodsObj.skuInfo.specList,
          goodsObj: goodsObj,
          originalGoodsObj: JSON.parse(JSON.stringify(goodsObj)),
          storeConfig: goodsObj.storeConfig,
          storeServiceList: storeServiceList,
          goodsId: goodsObj.goodsId,
          goodsBuyRule: goodsObj.goodsBuyRule,
          loading: false
        });
        console.log(this.data.shopCarInfo, goodsObj,'56565656656565')
        this.getBottomPrice()
        this.ifBuy();
        //如果是预售则直接预售 否则判断是否有秒杀或者拼团
        if (goodsObj.presell) {
          wx.hideLoading()
          this.defaultSkunFun(); //让用户默认选一个sku
          return
        }
        const params = {
          goodsId: res.data.goodsId,
          storeId: this.data.storeConfig.storeId
        }
        getGoodsActiveList(params).then(res => {
          wx.hideLoading()
          if (res.data.activityList.length > 0) {
            if(this.data.goodsType == 200){
              this.setData({
                'goodsObj.virtual':false,
                deliveryTypeShow:false
              })
            }
            //选取当前执行的活动
            this.handleActivity(res.data.activityList)
          } else {
            this.defaultSkunFun(); //让用户默认选一个sku
          }
          // this.ifBuy()//判断非会员是否可以购买
        })


      }).catch(() => {

      })
      this.cartListCountFunc();
    },
    handleGroupShopNum() {

    },
    //增加activityInfo对象的状态·
    // changActivityInfoAttribute(){
    //   this.setData({['activityInfo.groupEndTime']:dayjs(this.data.activityInfo.endTime).format('MM月DD日')})
    // },

    //判断当下选择什么活动
    handleActivity(list) {
      // 用户数据
      let isMember = this.data.isMember
      let memberStatus = this.data.memberStatus
      let cardId = this.data.cardId
      // 初始化
      list.forEach((v, i) => {
        // 判断用户权限
        if (v.rule.userLimit === 2 && (!v.rule.userLimitCards.includes(cardId) || !isMember || memberStatus !== 1) ||
          v.rule.userLimit === 1 && (!isMember || memberStatus !== 1)
        ) {
          console.log('判断用户权限', '无权限', v.activityNo)
          if (!this.data.joinSpellGroupInfo || this.data.joinSpellGroupInfo && this.data.joinSpellGroupInfo.groupNo !== v.activityNo) delete list[i] // 去除用户权限活动
          return
        }

        // 判断配送权限
        v.deliveryTypes = []
        // 商品配送方式
        this.data.goodsObj.goodsDelivery.forEach(goodsDeliveryItem => {
          v.deliveryTypes.push(goodsDeliveryItem.deliveryType)
        })
        // 拼团配送方式
        if (v.type === 'GROUP') {
          let deliveryTypes = []
          if (v.deliveryList && v.deliveryList.length) {
            v.deliveryList.forEach(deliveryItem => {
              if (deliveryItem.supply) deliveryTypes.push(deliveryItem.deliveryType)
            })
          }
          v.deliveryTypes = v.deliveryTypes.filter(function (delivery) {
            return deliveryTypes.indexOf(delivery) > -1
          }) // 获取交集
        }

        if (!v.deliveryTypes.length && this.data.goodsObj.goodsType !== 200) {
          console.log('判断快递', '无支持', v.activityNo)
          delete list[i] // 去除配送异常活动
          return
        }
        this.data.goodsObj.deliveryTypes = v.deliveryTypes
        // 判断限购
        v.buyNumLimit = -1 // -1不限购
        if (v.rule.perOrderLimit && v.rule.perUserLimit) {
          let userCanBuyNum = v.rule.perUserLimit - v.buyNum
          userCanBuyNum = userCanBuyNum < 0 ? 0 : userCanBuyNum
          v.buyNumLimit = v.rule.perOrderLimit < userCanBuyNum ? v.rule.perOrderLimit : userCanBuyNum
        } else if (v.rule.perUserLimit) {
          let userCanBuyNum = v.rule.perUserLimit - v.buyNum
          v.buyNumLimit = userCanBuyNum < 0 ? 0 : userCanBuyNum
        } else if (v.rule.perOrderLimit) {
          v.buyNumLimit = v.rule.perOrderLimit
        }

        // 去除购买上限限制
        if (v.buyNumLimit === 0) {
          console.log('判断限购buyNumLimit', '不可购买', v.activityNo)
          delete list[i]
          return
        }
        // 判断sku 状态 库存
        let skuList = []
        this.data.goodsObj.skuInfo.skuList.forEach(goodsSku => {
          if (goodsSku.status) {
            v.skuList.forEach(activitySku => {
              if (goodsSku.skuId === activitySku.skuId) {
                activitySku.status = 1
                activitySku.specAttrs = goodsSku.specAttrs
                activitySku.sn = goodsSku.sn
                if (activitySku.stockNum) skuList.push(activitySku)
              }
            })
          }
        })
        v.skuList = skuList
        // 去除sku异常状态 无库存
        if (!skuList.length) {
          console.log('判断skuList', '无skuList', v.activityNo)
          delete list[i]
          return
        }

        console.log('正常活动', v.activityNo)
        // 格式化数据
        v.skuListMap = {}
        v.skuListIds = []
        v.skuList.forEach(sku => {
          v.skuListIds.push(sku.skuId)
          v.skuListMap[sku.skuId] = sku
        })
      })
      const secKillActivityList = list.filter((item) => {
        if (item.type === "SEC_KILL") return true
      })
      const groupActivityList = list.filter((item) => {
        if (item.type === "GROUP") return true
      })
      console.log('secKillActivityList', secKillActivityList)
      console.log('groupActivityList', groupActivityList)
      groupActivityList.sort((a, b) => {
        return a.rule.groupJoinNum - b.rule.groupJoinNum
      })
      this.setData({
        secKillActivityList,
        groupActivityList
      })
      if (secKillActivityList.length || groupActivityList.length) {
        this.filterSkuActivity()
        this.setData({
          setInterValName: setInterval(() => {
            this.filterSkuActivity()
          }, 500)
        })
      } else {
        this.defaultSkunFun()
      }
    },

    // 过滤sku活动
    filterSkuActivity() {
      // 已有sku
      let activeSkuId = this.data.selectSkuObj && this.data.selectSkuObj.skuId || ''
      // 判断是否有可用sku
      let enableSkuIds = []
      // let hasStockNumEnableSkuIds=[]
      if (!activeSkuId) {
        // 获取可用skuIds
        this.data.goodsObj.skuInfo.skuList.forEach(v => {
          if (v.status) enableSkuIds.push(v.skuId)
          // if (v.status&&v.stockNum)  hasStockNumEnableSkuIds.push(v.skuId)
        })

        // 无可用sku return
        if (!enableSkuIds.length) {
          if (this.data.refreshSkuInfo) this.defaultSkunFun();
          return
        }
      }


      // step1 判断所有sku是否秒杀中
      let isSecKill = false
      let hasSecKillSkuActivityMap = {}
      if (this.data.secKillActivityList.length) {
        this.data.goodsObj.skuInfo.skuList.forEach((goodsSkuInfo, goodsSkuIndex) => {
          this.data.secKillActivityList.some(activity => {
            return activity.periodTimeList.some(time => {
              const secKillBeginTime = dayjs().format('YYYY-MM-DD') + ` ${Math.floor(time.beginTime / 60)}:${time.beginTime % 60}`;
              const secKillEndTime = dayjs().format('YYYY-MM-DD') + ` ${Math.floor(time.endTime / 60)}:${time.endTime % 60}`
              if (dayjs().isBefore(dayjs(secKillEndTime)) && dayjs().isAfter(dayjs(secKillBeginTime)) && dayjs().isBefore(activity.endTime) && dayjs().isAfter(activity.beginTime)) {
                // 判断sku在秒杀范围内覆盖库存值 只覆盖第一个进行中活动
                if (goodsSkuInfo.status && !Object.keys(hasSecKillSkuActivityMap).includes(String(goodsSkuInfo.skuId)) && activity.skuListIds.includes(goodsSkuInfo.skuId) && (activity.booking && activity.bookingStatus || !activity.booking)) {
                  let activityStockNum = activity.skuListMap[goodsSkuInfo.skuId].stockNum
                  if (activityStockNum !== this.data.goodsObj.skuInfo.skuList[goodsSkuIndex].stockNum) {
                    let todoParams = `goodsObj.skuInfo.skuList[${goodsSkuIndex}].stockNum`
                    this.setData({
                      [todoParams]: activityStockNum
                    })
                  }
                  activity.secKillBeginTime = secKillBeginTime
                  activity.secKillEndTime = secKillEndTime
                  hasSecKillSkuActivityMap[goodsSkuInfo.skuId] = JSON.parse(JSON.stringify(activity))
                }
                return true
              }
            })
          })
        })
        this.setData({
          hasSecKillSkuActivityMap
        })
      }

      // 判断当前sku是否在秒杀中
      if (Object.keys(hasSecKillSkuActivityMap).length && !activeSkuId) activeSkuId = Object.keys(hasSecKillSkuActivityMap)[0]
      if (Object.keys(hasSecKillSkuActivityMap).length && Object.keys(hasSecKillSkuActivityMap).includes(String(activeSkuId))) {
        let activity = hasSecKillSkuActivityMap[activeSkuId]
        // 倒计时
        let date1 = dayjs()
        let date2 = dayjs(activity.secKillEndTime)
        let hours = date2.diff(date1, 'hours')
        let minutes = date2.diff(date1, 'minutes') - Math.floor(date2.diff(date1, 'minutes') / 60) * 60
        let seconds = date2.diff(date1, 'seconds') - Math.floor(date2.diff(date1, 'seconds') / 60) * 60
        this.setData({
          skillHours: hours < 10 ? ("0" + hours) : hours,
          skillMinutes: minutes < 10 ? ("0" + minutes) : minutes,
          skillSeconds: seconds < 10 ? ("0" + seconds) : seconds
        })
        if (JSON.stringify(this.data.activityInfo) !== JSON.stringify(activity)) this.setData({
          activityInfo: activity
        })
        if (this.data.goodsTypeNew !== 'SEC_KILL') this.setData({
          goodsTypeNew: 'SEC_KILL'
        })
        if (this.data.bookingStatus !== 1) this.setData({
          bookingStatus: 1
        })
        if (!this.data.selectSkuObj) {
          this.defaultSkunFun(activeSkuId);
        } else if (this.data.refreshSkuInfo) {
          this.defaultSkunFun(activeSkuId);
        }
        console.log('step1 秒杀活动进行中')
        isSecKill = true
      }
      // 覆盖非秒杀中库存
      this.data.goodsObj.skuInfo.skuList.forEach((sku, skuIndex) => {
        if (!Object.keys(hasSecKillSkuActivityMap).includes(String(sku.skuId))) {
          if (this.data.originalGoodsObj.skuListMap[sku.skuId].stockNum !== this.data.goodsObj.skuInfo.skuList[skuIndex].stockNum) {
            let todoParams = `goodsObj.skuInfo.skuList[${skuIndex}].stockNum`
            this.setData({
              [todoParams]: this.data.originalGoodsObj.skuListMap[sku.skuId].stockNum
            })
          }
        }
      })
      if (isSecKill) {
        this.setData({
          quickSkillItem: null
        })
        this.setData({
          secKillBookingNoticeActivity: null,
          secKillBookingNotice: [],
          secKillBookingNoticeActive: null,
          groupBookingNotice: [],
          groupRecommends: []
        })
        return
      }



      // step2 判断团购进行中
      let isGroup = false
      let allStartingGroupList = []
      let allStartingGroupSkuIds = []
      let startingGroupList = []
      let featureGroupList = []
      if (this.data.groupActivityList.length) {
        this.data.groupActivityList.forEach(activity => {
          if (dayjs().isBefore(dayjs(activity.endTime)) && dayjs().isAfter(dayjs(activity.beginTime))) {
            allStartingGroupSkuIds = allStartingGroupSkuIds.concat(activity.skuListIds)
          }
        })
        allStartingGroupSkuIds = [...new Set(allStartingGroupSkuIds)];
        // 判断当前sku是否在拼团中
        if (allStartingGroupSkuIds.length && !activeSkuId) activeSkuId = allStartingGroupSkuIds[0]
        if (allStartingGroupSkuIds.length && this.data.joinSpellGroupStatue && !allStartingGroupSkuIds.includes(activeSkuId)) {
          activeSkuId = allStartingGroupSkuIds[0]
          this.setData({
            selectSkuObj: allStartingGroupSkuIds[0]
          })
        }
        if (allStartingGroupSkuIds.length && allStartingGroupSkuIds.includes(activeSkuId)) {
          this.data.groupActivityList.forEach(activity => {
            if (dayjs().isBefore(dayjs(activity.endTime)) && dayjs().isAfter(dayjs(activity.beginTime))) {
              activity.groupEndTime = dayjs(activity.endTime).format('MM月DD日')
              if (activity.skuListIds.includes(activeSkuId)) {
                activity.disable = false
                startingGroupList.push(activity)
                allStartingGroupList.push(activity)
              } else {
                activity.disable = true
                allStartingGroupList.push(activity)
              }
            } else {
              if (activity.skuListIds.includes(activeSkuId)) featureGroupList.push(activity)
            }
          })

          if (startingGroupList.length) {
            if (this.data.goodsTypeNew !== 'GROUP') this.setData({
              goodsTypeNew: 'GROUP'
            })
            if (this.data.bookingStatus !== 1) this.setData({
              bookingStatus: 1
            });
            if (JSON.stringify(this.data.groupList) !== JSON.stringify(allStartingGroupList)) this.setData({
              groupList: allStartingGroupList
            });
            // 判断是否已激活活动
            let isActive = false
            if (this.data.activityInfo && this.data.activityInfo.type === 'GROUP') {
              isActive = startingGroupList.some(startingGroup => {
                if (startingGroup.activityNo === this.data.activityInfo.activityNo) return true
              })
            }
            if (!isActive) {
              if (!this.data.activityInfo || this.data.activityInfo && JSON.stringify(this.data.activityInfo) !== JSON.stringify(startingGroupList[0])) this.setData({
                activityInfo: startingGroupList[0]
              })
            }
            // debugger
            if (!this.data.selectSkuObj) {
              this.defaultSkunFun(activeSkuId);
            } else if (this.data.refreshSkuInfo || !isActive) {
              this.defaultSkunFun(activeSkuId);
            }
            console.log('step2 团购进行中')
            isGroup = true
          }
        }
      }

      // step3 判断秒杀预约
      let secKillBooking = false
      if (this.data.secKillActivityList.length && activeSkuId) {
        this.data.secKillActivityList.some(activity => {
          if (activity.skuListIds.includes(activeSkuId)) {
            let secKillBookingNotice = []
            let dateIndex = 0
            // let maxLen = 2
            let maxLen = activity.booking ? 1 : 2
            let beginDate = dayjs().isBefore(activity.beginTime) ? activity.beginTime : dayjs()
            do {
              activity.periodTimeList.forEach((item) => {
                let hours = Math.floor(item.beginTime / 60)
                let minutes = item.beginTime % 60
                hours = hours < 10 ? ("0" + hours) : hours;
                minutes = minutes < 10 ? ("0" + minutes) : minutes;
                const bookTime = dayjs(beginDate).add(dateIndex, 'days').format('YYYY-MM-DD') + ` ${hours}:${minutes}`
                const bookDay = dayjs(beginDate).add(dateIndex, 'days').format('YYYY-MM-DD')
                const beginTime = dayjs(beginDate).add(dateIndex, 'days').format('YYYY-MM-DD') + ` ${Math.floor(item.beginTime / 60)}:${item.beginTime % 60}`;
                const endTime = dayjs(beginDate).add(dateIndex, 'days').format('YYYY-MM-DD') + ` ${Math.floor(item.endTime / 60)}:${item.endTime % 60}`
                if (dayjs().isBefore(dayjs(endTime)) && dayjs().isAfter(dayjs(beginTime)) && dayjs().isBefore(activity.endTime) && dayjs().isAfter(activity.beginTime)) {
                  let bookingTime = JSON.parse(JSON.stringify(item))
                  let day = "秒杀进行中";
                  bookingTime.isUnderway = true
                  bookingTime.bookDate = ''
                  bookingTime.timeText = `${day} 秒杀价￥${activity.skuListMap[activeSkuId].price / 100}`
                  if (secKillBookingNotice.length < maxLen) secKillBookingNotice.push(bookingTime)
                } else if (dayjs().isBefore(bookTime)) {
                  let bookingTime = JSON.parse(JSON.stringify(item))
                  let day = "";
                  if (bookDay === dayjs().format('YYYY-MM-DD')) {
                    day = "今天"
                  } else if (bookDay === dayjs().add(1, 'days').format('YYYY-MM-DD')) {
                    day = "明天"
                  } else {
                    day = dayjs(beginDate).add(dateIndex, 'days').format("MM月DD日")
                  }
                  bookingTime.isUnderway = false
                  bookingTime.bookDate = `${bookDay} ${hours}:${minutes}`
                  bookingTime.timeText = `${day} ${hours}:${minutes} 秒杀价￥${activity.skuListMap[activeSkuId].price / 100}`
                  if (secKillBookingNotice.length < maxLen) secKillBookingNotice.push(bookingTime)
                }
              })
              dateIndex += 1
            } while (secKillBookingNotice.length < maxLen && dayjs().add(dateIndex, 'days').isBefore(activity.endTime))
            if (secKillBookingNotice.length) {
              if (activity.booking && dayjs().isBefore(activity.bookingTime) || activity.bookingStatus || !activity.booking) {
                // this.setData({activityInfo:activity})
                // this.setData({goodsTypeNew:'SEC_KILL'})
                // this.setData({bookingStatus:0})
                if (JSON.stringify(this.data.secKillBookingNotice) !== JSON.stringify(secKillBookingNotice)) this.setData({
                  secKillBookingNotice: secKillBookingNotice
                })
                if (JSON.stringify(this.data.secKillBookingNoticeActivity) !== JSON.stringify(activity)) {
                  this.setData({
                    secKillBookingNoticeActivity: activity
                  })
                  this.setData({
                    secKillBookingNoticeActive: null
                  })
                }
                if (!isGroup) {
                  if (!this.data.selectSkuObj) {
                    this.defaultSkunFun(activeSkuId);
                  } else if (this.data.refreshSkuInfo) {
                    this.defaultSkunFun(activeSkuId);
                  }
                }
                console.log('step3 秒杀活动预约中')
                secKillBooking = true
                return true
              }
            }
          }
        })
      }
      if (!secKillBooking) {
        if (this.data.secKillBookingNoticeActivity !== null) this.setData({
          secKillBookingNoticeActivity: null
        })
        if (this.data.secKillBookingNotice !== []) this.setData({
          secKillBookingNotice: []
        })
        if (this.data.secKillBookingNoticeActive !== null) this.setData({
          secKillBookingNoticeActive: null
        })
      }
      if (isGroup) {
        this.setData({
          quickSkillItem: null
        })
        return;
      } else {
        if (this.data.activityInfo !== null) this.setData({
          activityInfo: null
        })
        if (this.data.bookingStatus !== 0) this.setData({
          bookingStatus: 0
        })
        if (this.data.groupRecommends !== []) this.setData({
          groupRecommends: []
        })
      }
      if (secKillBooking) {
        this.setData({
          quickSkillItem: null
        })
        return;
      }

      // step4 判断拼团预告
      let groupBooking = false
      if (featureGroupList.length && activeSkuId) {
        let groupBookingNotice = []
        featureGroupList.some(activity => {
          if (activity.skuListIds.includes(activeSkuId) && groupBookingNotice.length < 2) {
            let day = ""
            if (dayjs(activity.beginTime).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD')) {
              day = "今天"
            } else if (dayjs(activity.beginTime).format('YYYY-MM-DD') === dayjs().add(1, 'days').format('YYYY-MM-DD')) {
              day = "明天"
            } else {
              day = dayjs(activity.beginTime).format("MM月DD日")
            }
            activity.bookingText = `${day} ￥${activity.skuListMap[activeSkuId].price / 100}/${activity.rule.groupJoinNum}人团`
            groupBookingNotice.push(activity)
          }
          if (groupBookingNotice.length >= 2) return true
        })
        if (groupBookingNotice.length) {
          if (this.data.goodsTypeNew !== 'GROUP') this.setData({
            goodsTypeNew: 'GROUP'
          })
          if (this.data.bookingStatus !== 0) this.setData({
            bookingStatus: 0
          });
          if (JSON.stringify(this.data.groupBookingNotice) !== JSON.stringify(groupBookingNotice)) this.setData({
            groupBookingNotice: groupBookingNotice
          });
          if (!this.data.selectSkuObj) {
            this.defaultSkunFun(activeSkuId);
          } else if (this.data.refreshSkuInfo) {
            this.defaultSkunFun(activeSkuId);
          }
          console.log('step3 团购预约中')
          groupBooking = true
        }
      }
      if (!groupBooking) {
        this.setData({
          groupBookingNotice: []
        })
      }
      if (groupBooking) return;

      // step5 正常商品
      // console.log('正常商品')
      if (this.data.activityInfo !== null) this.setData({
        activityInfo: null
      })
      if (this.data.bookingStatus !== 0) this.setData({
        bookingStatus: 0
      })
      if (this.data.secKillBookingNoticeActivity !== null) this.setData({
        secKillBookingNoticeActivity: null
      })
      if (this.data.secKillBookingNotice !== []) this.setData({
        secKillBookingNotice: []
      })
      if (this.data.secKillBookingNoticeActive !== null) this.setData({
        secKillBookingNoticeActive: null
      })
      if (this.data.groupBookingNotice !== []) this.setData({
        groupBookingNotice: []
      })
      if (this.data.groupRecommends !== []) this.setData({
        groupRecommends: []
      });
      if (this.data.secKillActivityList.length > 0) {
        this.handleSkillActiveTip()
      }
      if (this.data.refreshSkuInfo) this.defaultSkunFun(activeSkuId || null);
    },

    // 初始化 sku

    //获取sku商品的活动
    setSelectSku(selectSkuObj) {
      if (!selectSkuObj) return
      let flag = false
      if (this.data.activityInfo && Object.keys(this.data.activityInfo).length && this.data.goodsTypeNew && this.data.bookingStatus) {
        flag = this.data.activityInfo.skuList.some((sku) => {
          if (sku.skuId === selectSkuObj.skuId) {
            sku.specShowList = selectSkuObj.specShowList
            this.setData({
              selectSkuObj: sku
            })
            // 获取拼团推荐
            if (this.data.goodsTypeNew === 'GROUP') {
              const params = {
                goodsId: this.data.goodsId,
                storeId: this.data.storeConfig.storeId
              }
              getGroupRecommends(params).then(res => {
                this.setData({
                  groupRecommends: res.data || []
                })
              })
            }
            return true
          }
        })

        if (!flag) {
          this.setData({
            selectSkuObj
          })
        }
      } else {
        this.setData({
          selectSkuObj
        })
      }
      let snCode = this.data.selectSkuObj && selectSkuObj.sn || this.data.goodsObj.barCode
      if (snCode) {
        if (flag && this.data.goodsTypeNew && this.data.bookingStatus && this.data.activityInfo && this.data.activityInfo.rule.singleGoodsDiscount || !flag && this.data.goodsObj.goodsBuyRule && this.data.goodsObj.goodsBuyRule.canUseDiscount) {
          this.getGoodActivityFun(snCode)
        } else {
          this.setData({
            activeList: null
          })
        }
        this.setData({
          snCode
        })
      } else {
        this.setData({
          snCode: null
        })
      }
    },

    // 设置激活sku group 提醒我预告
    // setFeatureGroupBookingList(){
    //   let selectSkuObj=this.data.selectSkuObj
    //   let featureGroupList=this.data.featureGroupList
    //   if(this.data.goodsTypeNew==='GROUP'&&!this.data.bookingStatus&&this.data.featureGroupList&&selectSkuObj){
    //     let featureGroupBookingList=[]
    //     featureGroupList.forEach(v=>{
    //       if(v.skuListMap[selectSkuObj.skuId]&&featureGroupBookingList.length<2){
    //         let day=null
    //         if(dayjs(v.beginTime).format('YYYY-MM-DD')===dayjs().format('YYYY-MM-DD')){
    //           day = "今天"
    //         }else   if(dayjs(v.beginTime).format('YYYY-MM-DD')===dayjs().add(1,'days').format('YYYY-MM-DD')){
    //           day = "明天"
    //         }else{
    //           day =  dayjs(v.beginTime).format("MM月DD日")
    //         }
    //         v.bookingText=`${day} ￥${v.skuListMap[selectSkuObj.skuId].price / 100}/${v.rule.groupJoinNum}人团`
    //         featureGroupBookingList.push(v)
    //       }
    //   })
    //     if(featureGroupBookingList.length){
    //       this.setData({featureGroupBookingList:featureGroupBookingList})
    //     }else{
    //       this.setData({featureGroupBookingList:[]})
    //     }
    //   }else{
    //     this.setData({featureGroupBookingList:[]})
    //   }
    // },

    // 过滤拼团list权限
    // filterGroupAuth(allGroupList){
    //   let isMember = this.data.isMember
    //   let memberStatus = this.data.memberStatus
    //   let isUser=null;
    //   let cardId = this.data.cardId;
    //   allGroupList.sort((item1,item2)=>{
    //     return  item1.rule.groupJoinNum-item2.rule.groupJoinNum
    //   });
    //   let nowGroupList=allGroupList.filter((item,index)=>{
    //     return dayjs().isBefore(dayjs(item.endTime))&&dayjs().isAfter(dayjs(item.beginTime))&&((item.rule.userLimit===2&&item.rule.userLimitCards.includes(cardId)&&memberStatus===1)||
    //       (item.rule.userLimit===1&&isMember&&memberStatus===1)||
    //       (item.rule.userLimit===0))
    //   })
    //   let featureGroupList=allGroupList.filter((item,index)=>{
    //     return dayjs().isBefore(dayjs(item.beginTime))&&((item.rule.userLimit===2&&item.rule.userLimitCards.includes(cardId)&&memberStatus===1)||
    //       (item.rule.userLimit===1&&isMember&&memberStatus===1)||
    //       (item.rule.userLimit===0))
    //   })
    //   let bookingStatus=nowGroupList.length?1:0
    //   this.setData({bookingStatus})
    //   if(nowGroupList.length){
    //     //获取拼团推荐
    //     const params = {goodsId:this.data.goodsId,storeId:this.data.storeConfig.storeId}
    //     getGroupRecommends(params).then(res=>{
    //       this.setData({groupRecommends:res.data||[]})
    //     })
    //     this.setData({goodsTypeNew:'GROUP'})
    //     this.setData({groupList:nowGroupList});
    //     this.setData({activityInfo:nowGroupList[0]})
    //     this.setData({['activityInfo.groupEndTime']:dayjs(this.data.activityInfo.endTime).format('MM月DD日')})
    //     this.handleGroup()
    //     this.defaultSkunFun();
    //     if(this.data.selectSkuObj) this.setSelectSku(this.data.activityInfo,this.data.selectSkuObj.skuId)
    //   }else if(featureGroupList.length){
    //     this.setData({bookingStatus:0})
    //     this.setData({goodsTypeNew:'GROUP'})
    //     this.setData({featureGroupList:featureGroupList});
    //     this.defaultSkunFun();
    //   }else{
    //     this.setData({bookingStatus:0})
    //     this.setData({goodsTypeNew:''})
    //     this.defaultSkunFun();
    //   }
    // },

    changSelSkuActive(e) {
      console.log('选择新拼团活动', e.detail)
      this.setData({
        refreshSkuInfo: true
      })
      this.setData({
        activityInfo: e.detail
      })
    },

    //计算当前时间到活动结束时间
    // calcTimeFn(type){
    //   let isMember = this.data.isMember
    //   let memberStatus = this.data.memberStatus
    //   let isUser=null;
    //   let cardId = this.data.cardId;
    //   if((this.data.activityInfo.rule.userLimit===2&&this.data.activityInfo.rule.userLimitCards.includes(cardId)&&memberStatus===1)||
    //       (this.data.activityInfo.rule.userLimit===1&&isMember&&memberStatus===1)||
    //       (this.data.activityInfo.rule.userLimit===0)){
    //       // if(!this.data.goodsTypeNew) this.setData({goodsTypeNew:type})
    //     isUser=true
    //   }else{
    //     // this.setData({goodsTypeNew:null})
    //     isUser=false
    //   }
    //   const bookingStatus = this.data.activityInfo.periodTimeList.some((item)=>{
    //     const beginStandardTime = dayjs().format('YYYY-MM-DD')+` ${Math.floor(item.beginTime/60)}:${item.beginTime%60}`;
    //     const endStandardTime = dayjs().format('YYYY-MM-DD')+` ${Math.floor(item.endTime/60)}:${item.endTime%60}`
    //     if(dayjs().isBefore(dayjs(endStandardTime))&&dayjs().isAfter(dayjs(beginStandardTime))&&dayjs().isBefore(this.data.activityInfo.endTime)&&dayjs().isAfter(this.data.activityInfo.beginTime)){
    //             const date1 = dayjs();
    //             const date2 = dayjs(endStandardTime);
    //             let hours = date2.diff(date1, 'hours');
    //             let minutes = date2.diff(date1, 'minutes') - Math.floor(date2.diff(date1, 'minutes')/60)*60;
    //             let seconds = date2.diff(date1, 'seconds') - Math.floor(date2.diff(date1, 'seconds')/60)*60;
    //               this.setData({
    //                 skillHours:hours<10?("0"+hours):hours,
    //                 skillMinutes:minutes<10?("0"+minutes):minutes,
    //                 skillSeconds:seconds<10?("0"+seconds):seconds
    //               })
    //       return true
    //     }
    //   });
    //   this.setData({bookingStatus:bookingStatus})
    //   // 预约列表
    //   let goodsObj=JSON.parse(JSON.stringify(this.data.goodsObj))
    //   let originalGoodsObj=JSON.parse(JSON.stringify(this.data.originalGoodsObj))
    //   if(bookingStatus){
    //     if(isUser&&this.data.activityInfo.booking&&this.data.activityInfo.bookingStatus===1||isUser&&!this.data.activityInfo.booking){
    //         // 设置库存
    //       let firstActivitySkuId=null
    //       originalGoodsObj.skuInfo.skuList.forEach(goodSku=>{
    //         this.data.activityInfo.skuList.forEach((activitySku,activitySkuIndex)=>{
    //           if(goodSku.skuId===activitySku.skuId){
    //             activitySku.status=goodSku.status
    //             goodSku.stockNum=activitySku.stockNum
    //             goodSku.price=activitySku.price
    //             goodSku.originPrice=activitySku.originPrice
    //             goodSku.specialPrice=activitySku.specialPrice
    //             if(!firstActivitySkuId&&activitySku.status&&activitySku.stockNum) firstActivitySkuId=activitySku.skuId
    //           }
    //         })
    //       })
    //       originalGoodsObj.secKillBuyNumLimit=this.data.activityInfo.buyNumLimit
    //       // console.log('商品秒杀限购secKillBuyNumLimit',originalGoodsObj.secKillBuyNumLimit)
    //       // 判断是否覆盖
    //       if(JSON.stringify(goodsObj)!==JSON.stringify(originalGoodsObj))  this.setData({goodsObj:originalGoodsObj})
    //       // 判断有没选择sku  没有默认活动第一个
    //       if(!this.data.selectSkuObj&&firstActivitySkuId){
    //         this.defaultSkunFun(firstActivitySkuId);
    //       }
    //       if(this.data.selectSkuObj&&this.data.refreshSkuInfo){
    //         this.defaultSkunFun(this.data.selectSkuObj.skuId);
    //       }
    //       // 判断是否秒杀活动sku
    //       if(this.data.selectSkuObj&&this.data.activityInfo.skuListIds.includes(this.data.selectSkuObj.skuId)){
    //         console.log('在秒杀时段 是秒杀sku')
    //         this.setData({goodsTypeNew:type})
    //       }else{
    //         console.log('在秒杀时段 非秒杀sku')
    //         this.setData({goodsTypeNew:null})
    //       }
    //     }else{
    //       console.log('在秒杀时段 被限制')
    //       this.setData({goodsTypeNew:null})
    //       // 判断有没选择sku  没有默认
    //       if(!this.data.selectSkuObj){
    //         this.defaultSkunFun();
    //       }else if(this.data.refreshSkuInfo){
    //         this.defaultSkunFun(this.data.selectSkuObj.skuId);
    //       }
    //     }
    //   }else{
    //     if(JSON.stringify(goodsObj)!==JSON.stringify(originalGoodsObj))  this.setData({goodsObj:originalGoodsObj})
    //     // 判断有没选择sku  没有默认
    //     if(!this.data.selectSkuObj){
    //       this.defaultSkunFun();
    //     }else if(this.data.refreshSkuInfo){
    //       this.defaultSkunFun(this.data.selectSkuObj.skuId);
    //     }
    //     // let selectSkuObj=this.data.selectSkuObj||this.data.activityInfo.skuList[0]
    //     let selectSkuObj=this.data.selectSkuObj
    //     // 判断是否在预约范围时间内
    //     if(selectSkuObj&&this.data.activityInfo.skuListIds.includes(selectSkuObj.skuId)&&
    //         (isUser&&this.data.activityInfo.booking&&this.data.activityInfo.bookingStatus===0&&dayjs().isBefore(this.data.activityInfo.bookingTime)||
    //         isUser&&this.data.activityInfo.booking&&this.data.activityInfo.bookingStatus===1||
    //         isUser&&!this.data.activityInfo.booking)
    //     ){
    //         let bookingTimeArr=[]
    //         let dateIndex=0
    //         let maxLen=2
    //         // let beginDate=this.data.activityInfo.beginTime
    //         let beginDate=dayjs().isBefore(this.data.activityInfo.beginTime)?this.data.activityInfo.beginTime:dayjs()
    //         do {
    //           this.data.activityInfo.periodTimeList.forEach((item,index)=>{
    //             let hours = Math.floor(item.beginTime/60)
    //             let minutes = item.beginTime%60
    //             hours=hours<10?("0"+hours):hours;
    //             minutes=minutes<10?("0"+minutes):minutes;
    //             const bookTime = dayjs(beginDate).add(dateIndex,'days').format('YYYY-MM-DD')+` ${hours}:${minutes}`
    //             const bookDay = dayjs(beginDate).add(dateIndex,'days').format('YYYY-MM-DD')
    //             if(dayjs().isBefore(bookTime)){
    //               let bookingTime=JSON.parse(JSON.stringify(item))
    //               let day = "";
    //               if(bookDay===dayjs().format('YYYY-MM-DD')){
    //                 day = "今天"
    //               }else if(bookDay===dayjs().add(1,'days').format('YYYY-MM-DD')){
    //                 day = "明天"
    //               }else{
    //                 day = dayjs(beginDate).add(dateIndex,'days').format("MM月DD日")
    //               }
    //               bookingTime.bookDate= `${bookDay} ${hours}:${minutes}`
    //               bookingTime.timeText=`${day} ${hours}:${minutes} 秒杀价￥${this.data.activityInfo.skuListMap[selectSkuObj.skuId].price/100}`
    //               if(bookingTimeArr.length<maxLen) bookingTimeArr.push(bookingTime)
    //             }
    //           })
    //           dateIndex+=1
    //         }while(bookingTimeArr.length<maxLen&&dayjs().add(dateIndex,'days').isBefore(this.data.activityInfo.endTime))
    //          if(bookingTimeArr.length){
    //            console.log('不在秒杀时段 无限制 是sku')
    //             this.setData({subscribeTimeArr:bookingTimeArr})
    //             this.setData({goodsTypeNew:type})
    //          }else{
    //            console.log('不在秒杀时段 无限制 是sku 无秒杀时段')
    //            this.setData({goodsTypeNew:null})
    //         }
    //     }else{
    //       console.log('不在秒杀时段 被限制 非sku')
    //       this.setData({goodsTypeNew:null})
    //     }
    //
    //   }
    //
    //   // const bookingStatus = this.data.activityInfo.periodTimeList.some((item,index)=>{
    //   //   const beginStandardTime = new Date().getFullYear() +"-"+(new Date().getMonth()+1)+"-"+new Date().getDate()+" "+ Math.floor(item.beginTime/60) +":"+ (item.beginTime-Math.floor(item.beginTime/60)*60);
    //   //   const endStandardTime =  new Date().getFullYear() +"-"+(new Date().getMonth()+1)+"-"+new Date().getDate()+" "+ Math.floor(item.endTime/60) +":"+ (item.endTime-Math.floor(item.endTime/60)*60)
    //   //   if(dayjs().isBefore(dayjs(endStandardTime))&&dayjs().isAfter(dayjs(beginStandardTime))){
    //   //     return true
    //   //   }
    //   // });
    //   // this.setData({bookingStatus:bookingStatus})
    //   // this.data.activityInfo.periodTimeList.forEach((item,index)=>{
    //   //   const beginStandardTime = new Date().getFullYear() +"-"+(new Date().getMonth()+1)+"-"+new Date().getDate()+" "+ Math.floor(item.beginTime/60) +":"+ (item.beginTime-Math.floor(item.beginTime/60)*60);
    //   //   const endStandardTime =  new Date().getFullYear() +"-"+(new Date().getMonth()+1)+"-"+new Date().getDate()+" "+ Math.floor(item.endTime/60) +":"+ (item.endTime-Math.floor(item.endTime/60)*60)
    //   //   if(dayjs().isBefore(dayjs(endStandardTime))&&dayjs().isAfter(dayjs(beginStandardTime))){
    //   //     const date1 = dayjs();
    //   //     const date2 = dayjs(endStandardTime);
    //   //     let hours = date2.diff(date1, 'hours');
    //   //     let minutes = date2.diff(date1, 'minutes') - Math.floor(date2.diff(date1, 'minutes')/60)*60;
    //   //     let seconds = date2.diff(date1, 'seconds') - Math.floor(date2.diff(date1, 'seconds')/60)*60;
    //   //       this.setData({
    //   //         skillHours:hours<10?("0"+hours):hours,
    //   //         skillMinutes:minutes<10?("0"+minutes):minutes,
    //   //         skillSeconds:seconds<10?("0"+seconds):seconds
    //   //       })
    //   //   }else {
    //   //     //当前时间不在秒杀活动时间 查询当前时间后的秒杀时间数组
    //   //     let subscribeTimeArr = this.data.activityInfo.periodTimeList.filter((item,index)=>{
    //   //       const beginStandardTime = new Date().getFullYear() +"-"+(new Date().getMonth()+1)+"-"+new Date().getDate()+" "+ Math.floor(item.beginTime/60) +":"+ (item.beginTime-Math.floor(item.beginTime/60)*60);
    //   //       return  dayjs().isBefore(dayjs(beginStandardTime))?true:false;
    //   //     })
    //   //     if(subscribeTimeArr.length>0){
    //   //       subscribeTimeArr.sort((item1,item2)=>{
    //   //         return item1.beginTime - item2.beginTime
    //   //       })
    //   //       subscribeTimeArr.map((item,index)=>{
    //   //         let hours = Math.floor(item.beginTime/60);
    //   //         let minutes = item.beginTime-Math.floor(item.beginTime/60)*60;
    //   //         let month = new Date().getMonth()+1;
    //   //         let days = new Date().getDate()
    //   //         hours=hours<10?("0"+hours):hours;
    //   //         minutes=minutes<10?("0"+minutes):minutes;
    //   //         item.timeText = dayjs().format(`${month}月${days}日 ${hours+":"+minutes} 秒杀价￥${this.data.selSkuActive.price/100}`)
    //   //         return item
    //   //       })
    //   //       this.setData({subscribeTimeArr})
    //   //     }
    //   //
    //   //   }
    //   // })
    //
    //
    //
    // },
    cartListCountFunc() {
      const self = this;
      let temp = {
        cartType: 0,
        mode: 1
      }
      cartListCount(temp).then(res => {
        if (res.code == 0) {
          self.setData({
            cartCount: res.data
          })
        }
      })
    },
    //查看其他商品
    viewOther() {
      let storeId = this.data.storeConfig.storeId
      router.push({
        name: "mall/goods-list",
        params: {
          storeId
        }
      })
    },
    //显示tost提示框
    showTost(state) {
      this.setData({
        hiddentost: false,
        tostState: state
      })
      setTimeout(() => {
        this.setData({
          hiddentost: true,
        })
      }, 1000)
    },
    //计算商品sku最低价格
    getBottomPrice() {
      let skuList = JSON.parse(JSON.stringify(this.data.skuList));
      let compare = function (obj1, obj2) {
        let val1 = obj1.price;
        let val2 = obj2.price;
        if (val1 < val2) {
          return -1;
        } else if (val1 > val2) {
          return 1;
        } else {
          return 0;
        }
      }
      let temp = (skuList.sort(compare))
      console.log('showPriceObj', temp[0])
      this.setData({
        showPriceObj: temp[0]
      })
    },

    // 设置默认sku
    defaultSkunFun(selectSkuId = null) {
      console.log('defaultSkunFun', selectSkuId)
      // this.setData({selectSkuObj:null})
      const self = this;
      let skuList = this.data.goodsObj.skuInfo.skuList;
      let specList = JSON.parse(JSON.stringify(this.data.specList));
      let tempdata = [];
      let skuId = selectSkuId;
      let tempBoolean = true
      //判断selectSkuObj是否为空
      if (self.data.selectSkuObj) {
        skuId = self.data.selectSkuObj.skuId ? self.data.selectSkuObj.skuId : null;
      }

      //先判断已选对象是否有skuId
      if (skuId) {
        console.log("进if")
        //临时数组
        let tmp = []
        //循环找出指定skuid的对象
        skuList.forEach(item => {
          if (item.skuId === parseInt(skuId)) {
            tmp.push({
              ...item
            })
          }
        })
        console.log('tmp', tmp, this.data.goodsTypeNew)
        if (tmp[0].status && tmp[0].stockNum > 0 || tmp[0].status && selectSkuId) {
          let r = tmp[0].specAttrs.filter(s => s);
          console.log('r', r)
          let specShowList = []
          //循环specList数组 ，如果目标数组中含有specList数组的id 就放入 spec展示list里面
          specList.forEach(item => {
            let attrs = item.attrList;
            attrs.forEach(item2 => {
              if (r.includes(item2.id)) {
                specShowList.push(item2)
              }
            });
          });
          tmp[0].specShowList = specShowList;
          this.setSelectSku(tmp[0])
          tempBoolean = false;
        } else {
          tempBoolean = true;
        }
      }
      //没有sku id 已选skuid库存为0 或者已下架
      if (tempBoolean) {
        console.log("进else")
        skuList.forEach(item => {
          //   console.log('item', item)
          if (tempdata.length < 1) {
            if (item.status && item.stockNum) {
              tempdata.push(item)
              // this.getGoodActivityFun(item.sn)
              // this.setData({snCode:item.sn})
            }
          }
        })
        if (specList.length > 0 && tempdata.length) {
          let r = tempdata[0].specAttrs.filter(s => s);
          //console.log("fu里面的r", r)
          let specShowList = []
          //循环specList数组 ，如果目标数组中含有specList数组的id 就放入 spec展示list里面
          specList.forEach(item => {
            let attrs = item.attrList;
            attrs.forEach(item2 => {
              if (r.includes(item2.id)) {
                specShowList.push(item2)
                //  console.log("specShowList", specShowList);
              }
            });
          });
          tempdata[0].specShowList = specShowList;
        }
        this.setSelectSku(tempdata[0]);
      }
      this.data.refreshSkuInfo = false

      if (Object.keys(this.data.shopCarInfo).length > 0 && !this.data.shopCarInfoNum) {
        this.setData({
          showSkuDialog: true,
          shopCarInfoNum: 1
        });
      }
    },

    // 设置选择sku
    setSelectSkuBySkuId(skuId) {
      let skuList = this.data.goodsObj.skuInfo.skuList
      let specList = JSON.parse(JSON.stringify(this.data.specList))
      //临时数组
      let tmp = []
      //循环找出指定skuid的对象
      skuList.some(item => {
        if (item.skuId === parseInt(skuId)) {
          tmp.push(item)
          return true
        }
      })
      let r = tmp[0].specAttrs.filter(s => s);
      let specShowList = []
      specList.forEach(item => {
        let attrs = item.attrList;
        attrs.forEach(item2 => {
          if (r.includes(item2.id)) {
            specShowList.push(item2)
          }
        });
      });
      tmp[0].specShowList = specShowList;
      this.setData({
        selectSkuObj: tmp[0],
      })
    },

    //虚拟商品选择sku
    virtualDefaultSkunFun() {
      const self = this;
      let sku = self.data.skuList[0];
      self.setData({
        selectSkuObj: sku
      })
      // if(Object.keys(this.data.activityInfo).length>0){
      //   this.setSelectSku(this.data.activityInfo,self.data.skuList[0].skuId)
      // }
    },

    async handleBuyNow(e) {
      let setShopStatus = await this.setShopStatus()
      if (!setShopStatus) return
      // 判断是否是点击凑团进来的
      if (e.currentTarget.dataset.grouprecommendsitems) {
        const options = e.currentTarget.dataset.grouprecommendsitems
        this.data.groupList.some((v, i) => {
          if (v.rule.groupJoinNum === e.currentTarget.dataset.grouprecommendsitems.joinNum) {
            this.setData({
              ['goodsObj.deliveryTypes']: v.deliveryTypes
            })
          }
        })
        this.setData({
          aboutGroupInfoItem: options,
          groupNo: options.groupNo,
          groupActivityNo: options.activityNo,
          oneselfGroup: false,
          joinGroupOrigin: "collect",
          groupShopType: e.currentTarget.dataset.shoptype

        });
      }
      //判断是否是点击参团进来的
      if (e.currentTarget.dataset.type === 'joinSpellGroup') {
        const options = this.data.joinSpellGroupInfo;
        this.setData({
          aboutGroupInfoItem: options,
          groupNo: options.groupNo,
          groupActivityNo: options.groupActivityNo,
          oneselfGroup: false,
          joinGroupOrigin: "tuxedo"
        });
      }
      //判断是否点击我要开团m
      if (e.currentTarget.dataset.shoptype && !e.currentTarget.dataset.grouprecommendsitems) {
        this.setData({
          groupShopType: e.currentTarget.dataset.shoptype,
          groupShopStatus: e.currentTarget.dataset.groupshopstatus,
          ['goodsObj.deliveryTypes']: this.data.originalGoodsObj.deliveryTypes
        })
      }
      // groupShopType==='openGroup'&&goodsTypeNew==='GROUP'
      if(!this.data.goodsObj.virtual&&this.data.goodsObj.goodsType == 200){
        this.setData({
          groupShopType: 'openGroup',
          groupShopStatus: true,
        })
      }


      if (this.data.goodsObj.virtual) {
        let countObj = {
          count: 1,
          oneselfGroup: false
        }
        this.buyNow(countObj);
      } else {
        this.handleAddCart();
      }
    },
    async setShopStatus() {
      let {
        storeId
      } = this.data.tempdata
      let isOpenTime = true
      let res = await getShopStatus({
        storeId
      })
      let {
        isOpen,
        status,
        disabled
      } = res.data
      isOpenTime = isOpen == true && (status == 1 || status == 2) && disabled == false ? true : false
      this.setData({
        isOpenTime
      })
      return isOpenTime
    },
    //判断是否需要秒杀预约
    judegBookingStatus() {
      if (!this.data.activityInfo) return true
      if (this.data.activityInfo.booking) {
        if (this.data.activityInfo.bookingStatus) {
          return true
        } else {
          return false
        }
      } else {
        return true
      }
    },
    //点击立即购买按钮
    buyNow(countObj) {
      console.log(countObj,'*******************************');
      // const bookingStatus=this.judegBookingStatus();
      // if(!bookingStatus){
      //   wx.showToast({title: "需要提前预定哦！", icon: 'none', duration: 1500});
      //   return;
      // }
      //声明参数
      let dataTemp = {}
      let items = []
      let selectSkuObj = JSON.parse(JSON.stringify(this.data.selectSkuObj));
      let goodsObj = JSON.parse(JSON.stringify(this.data.goodsObj));
      if (countObj.count) { } else {
        if (!goodsObj.virtual && goodsObj.skuInfo.skuList.length > 1) {
          this.setData({
            showSkuDialog: true
          })
          countObj.count = 1
          return;
        } else {
          countObj.count = 1
        }
      }

      /**
       * 进这里有两种可能
       * 1.虚拟商品进这个，不需要携带参数 只有一个skuid
       * 2.实物商品，要携带商品数量
       */
      //判断店铺状态
      if (this.data.storeConfig.status !== 1) {
        console.log('进这个')
        wx.showToast({
          title: '店铺已打样噢',
          icon: 'none'
        })
        return;
      }
      let deliveryType = "VIRTUAL";
      if (this.data.deliveryType === 'none') {
        wx.showToast({
          title: '店铺暂无配送方式',
          icon: 'none'
        })
        return;
      }
      deliveryType = goodsObj.virtual ? 'VIRTUAL' : this.data.deliveryType
      let orderPreForm = {
        goodsId: goodsObj.goodsId,
        num: goodsObj.virtual ? 1 : countObj.count,
        skuId: selectSkuObj.skuId,
        storeId: goodsObj.storeConfig.storeId,
        children: this.data.collList,
        price: this.data.selectSkuObj.price
      }
      if(goodsObj.goodsType == 200 && !goodsObj.virtual){
        deliveryType = 'VIRTUAL'
        // orderPreForm.activityType = this.data.activityInfo.type;
        // orderPreForm.activityNo = this.data.activityInfo.activityNo;
      }
      if (this.data.activityInfo && !countObj.oneselfGroup || this.data.activityInfo && this.data.goodsTypeNew === 'SEC_KILL') {
        console.log("this.data.activityInfo", this.data.activityInfo)
        let orderFrom = {
          activityNo: this.data.activityInfo.activityNo,
        }
        if (this.data.goodsTypeNew && this.data.bookingStatus && this.data.groupShopType !== 'oneSelf') {
          orderPreForm.activityType = this.data.activityInfo.type;
          orderPreForm.activityNo = this.data.activityInfo.activityNo;
          orderFrom.activityType = this.data.activityInfo.type;
        }
        if (this.data.joinGroupStatus) {
          orderFrom.activitySceneStr = this.data.groupNo
        }
        dataTemp.orderFrom = orderFrom
      }

      items.push(orderPreForm)
      dataTemp.items = items;
      dataTemp.source = 1;
      dataTemp.storeId = goodsObj.storeConfig.storeId
      dataTemp.type = deliveryType;
      //表示目前是秒杀状态
      console.log('countObj', countObj)
      if (this.data.goodsObj.presell) {
        dataTemp.subType = "PRESELL"
      } else if (this.data.goodsTypeNew === 'GROUP' && this.data.bookingStatus && !countObj.oneselfGroup) {
        dataTemp.subType = "GROUP"
      } else if (this.data.goodsTypeNew === 'SEC_KILL' && this.data.bookingStatus) {
        dataTemp.subType = "SEC_KILL"
      } else {
        dataTemp.subType = ""
      }
      console.log(dataTemp,'创建预订单====================');
      preOrderFun(dataTemp).then(res => {
        if (res.code === 0) {
          //虚拟商品
          if (goodsObj.virtual || goodsObj.goodsType == 200) {
            router.push({
              name: 'mall/submit-order-virtual',
              params: {
                preNo: res.data.preNo,
                storeNo: this.data.goodsObj.storeConfig.storeNo
              }
            })
          } else { //非虚拟商品
            router.push({
              name: 'mall/submit-order',
              params: {
                preNo: res.data.preNo,
                snCode: this.data.snCode,
                storeNo: this.data.goodsObj.storeConfig.storeNo
              }
            })
          }
        } else {
          wx.showToast({
            title: '购买失败，晚点试试把',
            icon: 'none',
            duration: 3000
          })
        }
      }).catch(res => {
        if (res.data.code === 55102) {
          let tipGoodsName = ""
          res.data.data.invalidItems.forEach((v, i) => {
            tipGoodsName += v.title + "、"
          })
          wx.showToast({
            title: `商品${tipGoodsName}库存不足哦！`,
            icon: 'none',
            duration: 1500
          })
        }
      })
    },
    //判断是否能够购买
    ifBuy() {
      console.log('ifBuy')
      this.setData({
        buyingTips: ''
      })
      const self = this;
      let cardIdList = this.data.goodsBuyRule.cardIdList;
      let cardList = this.data.goodsBuyRule.cardList;
      let memberType = this.data.goodsBuyRule.memberType;
      let isMember = this.data.isMember
      let memberStatus = this.data.memberStatus
      let cardId = this.data.cardId;
      // if(this.data.activityInfo){
      //   if((this.data.activityInfo.rule.userLimit===2&&this.data.activityInfo.rule.userLimitCards.includes(cardId)&&memberStatus===1)||(this.data.activityInfo.rule.userLimit===1&&isMember&&memberStatus===1)||(this.data.activityInfo.rule.userLimit===0)){
      //   return
      //   }else{
      //     this.setData({goodsTypeNew:null})
      //   }
      // }

      if (memberType === 1 && !isMember) {
        if (!isMember) {
          this.setData({
            buyingTips: '亲，要先开通会员才可以购买专享商品噢'
          })
        } else if (Number(memberStatus) !== 1) {
          this.setData({
            buyingTips: '亲，你的会员已过期, 请续费后再购买专享商品'
          })
        }
      }
      if (memberType === 2) {
        let temp = cardIdList.includes(cardId);
        if (!temp) {
          let tempStr = cardList.join("/")
          tempStr = "亲亲，要先开通" + tempStr + "才可以购买专享商品噢"
          self.setData({
            buyingTips: tempStr,
          })
        }
        if (Number(memberStatus) !== 1) {
          this.setData({
            buyingTips: '亲，你的会员已过期, 请续费后再购买专享商品'
          })
        }
      }
    },
    //去开卡页面
    openCard() {
      let urlParams = [{
        page: 'mine'
      }, {
        data: null
      }];
      urlParams = JSON.stringify(urlParams);
      console.log('urlParams', urlParams)
      let goodsDetail = true;
      router.push({
        name: 'indexChooseCard',
        params: {
          goodsDetail: goodsDetail
        }
      })
    },
    //显示分享按钮
    setShareShow() {
      this.setData({
        hiddenShare: false
      })
    },
    handleDeliveryType(e) {
      this.setData({
        deliveryType: e.detail
      })
    },
    async handleAddCart() {
      //
      let setShopStatus = await this.setShopStatus()
      if (!setShopStatus) return
      if (!this.data.goodsObj.virtual) {
        this.setData({
          showSkuDialog: true
        })
      } else {
        this.addCartFunc()
      }
    },
    //加入购物车
    addCartFunc(countObj) {
      let deliveryType = this.data.deliveryType;
      // if (deliveryType === 'SELF_PICKUP') {
      //   deliveryType = 'LOCAL'
      // }
      if (this.data.selectSkuObj) {
        let tempData = {
          goodsId: this.data.goodsId,
          children: countObj.collList.length > 0 ? countObj.collList : [],
          num: countObj.count ? countObj.count : 1,
          skuId: this.data.selectSkuObj.skuId,
          storeId: this.data.storeConfig.storeId,
          type: deliveryType,
          // type:'thirdValue',
          cartType: 0,
        };
        if (!this.data.deliveryType) {
          wx.showToast({
            title: '店铺暂无配送方式',
            icon: 'none'
          })
          return;
        }
        //同城配送商品，点击加入购物车，跳到家购买页
        if (deliveryType === 'LOCAL' && this.data.goodsBuyRule.canLocalDelivery && this.data.storeConfig.openShelfCategory) {
          let params = {
            ...tempData,
            goodsSerial: this.data.goodsObj.goodsSerial
          }

          router.push({
            name: 'mall/store-buy',
            params: {
              storeId: this.data.storeConfig.storeId,
              deliveryType: this.data.deliveryType,
              goodsSerial: this.data.goodsObj.goodsSerial
            },
            success: (res => {
              res.eventChannel.emit('addCart', params)
            })
          })
          return;
        }
        addGoodsToCart(tempData).then(res => {
          // 更新店铺id
          this.setStoreId(tempData.storeId);
          this.cartListCountFunc()
          this.setData({
            hiddentost: false,
            tostState: 'success',
          })
          setTimeout(() => {
            this.setData({
              hiddentost: true
            })
          }, 1000)
        })
      } else {
        //打开选择sku对话框
        this.setData({
          showSkuDialog: true
        })
      }
    },
    //监听加入购物车
    addCart(detail) {
      let countObj = {
        count: detail.detail,
        collList: this.data.collList
      }
      console.log("countObj", this.data.countObj);

      this.addCartFunc(countObj)
    },
    //增加搭配商品
    addColl(detail) {
      this.setData({
        collList: detail.detail
      })
    },
    //判断商品是否已下架或者店铺是否打样
    // refresh() {
    //   const self = this;
    //   getGoodDetail(this.data.tempdata).then(res => {
    //     if (res.code === 0) {
    //       let goodsObj = res.data;
    //       self.setData({
    //         goodsBargains:goodsObj.goodsBargains,
    //         goods: goodsObj.goods,
    //         goodsStatus: goodsObj.goodsStatus,
    //         //100: 普通商品, 200: 虚拟商品卡券
    //         goodsType: goodsObj.goodsType,
    //         skuList: goodsObj.skuInfo.skuList,
    //         specList: goodsObj.skuInfo.specList,
    //         goodsObj: goodsObj,
    //         storeConfig: goodsObj.storeConfig,
    //         goodsId: goodsObj.goodsId,
    //         goodsBuyRule: goodsObj.goodsBuyRule
    //       });
    //
    //       //获取最低价对象来展示
    //       self.getBottomPrice()
    //       //默认选择一个sku
    //       self.defaultSkunFun();
    //     }
    //   })
    // },
    //工具类函数
    //监听子组件传来的加入购物车
    // minitorAddcart(detail) {
    //   console.log('detail', detail.detail);
    //   this.addCartFunc({ count: detail.detail.count,collList:detail.detail.count });
    // },
    //监听子组件传过来的sku
    skuObjFun(detail) {
      console.log('子组件sku', detail)
      if (detail.detail) {
        this.setData({
          refreshSkuInfo: true
        })
        let r;
        if (detail.detail.specAttrs) {
          r = detail.detail.specAttrs.filter(s => s)
        }
        let specList = this.data.specList;
        let specShowList = [];
        // clearInterval(this.data.setInterValName)
        // this.getGoodActivityFun(detail.detail.sn);
        // this.setData({snCode:detail.detail.sn});
        // this.ifBuy()//判断非会员是否可以购买
        specList.forEach(item => {
          let arrList = item.attrList;
          arrList.forEach(item2 => {
            if (r && r.includes(item2.id)) {
              specShowList.push(item2);
            }
          })
        })
        detail.detail.specShowList = specShowList
        this.setSelectSku(detail.detail)
        if (this.data.secKillActivityList.length > 0) {
          this.handleSkillActiveTip()
        } else {
          this.setData({
            quickSkillItem: null
          })
        }
        // this.setData({
        //   selectSkuObj: detail.detail,
        //   'selectSkuObj.specShowList': specShowList
        // });
        // if(this.data.activityInfo&&Object.keys(this.data.activityInfo).length>0) {
        //   this.setSelectSku(detail.detail)
        // }
      }
    },

    //监听子组件是否有购买事件
    specBuyNowFunc(val) {
      console.log("specBuyNowFunc", val.detail);
      let countObj = {
        count: val.detail.count,
        oneselfGroup: val.detail.oneselfGroup
      };
      this.setData({
        oneselfGroup: val.detail.oneselfGroup,
        joinGroupStatus: val.detail.joinGroupStatus
      })
      this.buyNow(countObj)
    },
    //去购物车页面
    goShopCart() {
      router.push({
        name: 'mall/shop-cart'
      })
    },
    //去店铺详情页
    goMerchantDetail() {
      router.push({
        name: 'mall/store-detail',
        params: {
          storeId: this.data.storeConfig.storeId
        }
      })
    },
    handleSkuShow() {
      this.setData({
        showSkuDialog: true
      })
    },
    handleGoodActivityShow() {
      this.setData({
        showGoodActivityDialog: true
      });
    },
    enterSkill() {
      const detail = this.data.quickSkillItem
      this.skuObjFun({
        detail
      })
    },
    handleSelectStore() {
      if (this.data.skuList.length === 0) {
        wx.showToast({
          title: '当前商品尚未配置sku',
          icon: 'none'
        })
        return;
      }
      let skuId = this.data.skuList[0].skuId
      if (this.data.selectSkuObj) {
        skuId = this.data.selectSkuObj.skuId
      }
      let params = {
        goodsId: this.data.goodsObj.goodsId,
        goodsSerial: this.data.goodsObj.goodsSerial,
        skuId: skuId,
        virtual: this.data.goodsObj.virtual,
        skuNum: this.data.skuList.length,
        selectSkuObj: this.data.selectSkuObj ? JSON.parse(JSON.stringify(this.data.selectSkuObj)) : null,
        currentStoreId: this.data.tempdata.storeId
      }
      // console.log(this.data.tempdata)
      this.selectComponent("#selectStoreBuy").open(params);
    },
    handleChangeStore(e) {
      let store = e.detail;
      let tempdata = this.data.tempdata
      tempdata.storeId = store.storeId;
      this.setData({
        tempdata: tempdata,
        selectSkuObj: null,
        quickSkillItem: null
      });
      this.setStoreId(store.storeId);
      this.getGoodsDetailFun(tempdata);
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      });
      setTimeout(res => {
        wx.showToast({
          title: "已切换到" + store.name,
          icon: "none",
          duration: 1500
        })
        this.setShopStatus()
      }, 500)
    },
    handleStoreList(e) {
      let storeList = e.detail;
      let storeId = this.data.storeConfig.storeId;
      let hasOtherStore = false;
      for (let i = 0; i < storeList.length; i++) {
        if (storeList[i].storeId !== storeId) {
          hasOtherStore = true;
        }
      }
      this.setData({
        storeList: storeList,
        hasOtherStore: hasOtherStore
      })
    },
    onShareAppMessage(e) {
      let that = this;
      let tempdata = JSON.stringify(this.data.tempdata);
      return {
        title: that.data.goods.title,
        imageUrl: getApp().toFullUrl(that.data.goods.imgList[0]),
        path: '/sp-mall/pages/goods-detail/index?tempdata=' + tempdata,
        success: (res) => {
          that.setData({
            hiddenShare: true
          })
        }
      }
    },
    //找出正常sku时 其他sku秒杀项
    handleSkillActiveTip() {
      // console.log(this.data.specList)
      let specAttrs;
      let attrList = [];
      let quickSkillItem;
      const quickSkillItemStatus = this.data.secKillActivityList.some((v, i) => {
        return v.skuList.some((v2, i2) => {
          quickSkillItem = v2
          this.data.skuList.some((v4, i4) => {
            if (v4.skuId === v2.skuId) {
              specAttrs = v4.specAttrs.filter(Boolean)
              specAttrs.forEach((v4, i4) => {
                this.data.specList.forEach((v5, i5) => {
                  v5.attrList.some((v6, i6) => {
                    if (v4 === v6.id) {
                      attrList.push(v6.title)
                    }
                  })
                })
              })
            }
          })
          return true
        })
      })
      // debugger
      if (!Object.keys(this.data.hasSecKillSkuActivityMap).length) {
        this.setData({
          quickSkillItem: null
        })
        return
      }
      if (!quickSkillItemStatus) {
        this.setData({
          quickSkillItem: null
        })
      } else {
        quickSkillItem.attrList = attrList
        this.setData({
          quickSkillItem
        })
      }
    },
    onPullDownRefresh: function () {
      this.getGoodsDetailFun(this.data.tempdata)
      this.setData({
        shopCarInfo: []
      })
      wx.stopPullDownRefresh();
    },
    onUnload: function () {
      if (this.data.setInterValName) {
        clearInterval(this.data.setInterValName)
      }
    },
    onHide: function () {
      if (this.data.groupActivityNo) {
        this.setData({
          groupActivityNo: null
        })
      }
      if (this.data.setInterValName) {
        clearInterval(this.data.setInterValName)
      }
    },
    onShow: function () {
      if (this.data.firstShow) {
        this.setData({
          firstShow: false
        })
      } else {
        this.getGoodsDetailFun(this.data.tempdata);
        // this.refresh();
        this.cartListCountFunc();
        this.setData({
          showSkuDialog: false,
          oneselfGroup: true,
          groupType: true
        })
      }
    },
  }
})